package com.scut.campus.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.scut.campus.dto.PageDTO;
import com.scut.campus.entity.Type;
import com.scut.campus.response.Result;
import com.scut.campus.service.CommonService;
import com.scut.campus.service.TypeService;
import com.scut.campus.vo.BackgroundVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/common")
@Slf4j
@Tag(name = "通用功能")
public class CommonController {
    @Autowired
    private TypeService typeService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private CommonService commonService;


/*    @Operation(summary = "查询所有帖子分类")
    @GetMapping("/queryType")
    public Result<List<Type>> getType(){




        List<Type> typeList=typeService.getType();



        return Result.success(typeList);
    }*/


    @Operation(summary = "查询所有帖子分类")
    @GetMapping("/queryType")
    public Result<List<Type>> getType()  {
        //0、声明redis的key
        String key = "mainType";

        //1、从redis查询缓存
        //String typeJson=stringRedisTemplate.opsForValue().get(key);


        //typeReference  类型引用，用于指定反序列化的列表类型
        //TypeReference<List<Type>>res=new TypeReference<List<Type>>() {};


        //2、判断是否存在
        /*if(StrUtil.isNotBlank(typeJson)){
            //存在直接返回
            List<Type>resList=objectMapper.readValue(typeJson,res);
            System.out.println("由redis返回");
            return Result.success(resList);
        }*/

        //3、不存在，从数据库查询
        List<Type> typeList = typeService.getType();
        //4、插入redis
        //stringRedisTemplate.opsForValue().set(key,objectMapper.writeValueAsString(typeList));
        return Result.success(typeList);


    }


    @Operation(summary = "查询轮播图")
    @GetMapping("/getBackground")
    public Result<PageDTO<BackgroundVo>> getBackground() {
        List<BackgroundVo> backgroundVos =
                commonService.listBackground();
        PageDTO<BackgroundVo> res = new PageDTO<>();
        res.setList(backgroundVos);
        res.setTotal((long) backgroundVos.size());
        return Result.success(res);
    }
}
